Optimizing Images, Assets, and Network Requests in React Native
Course: React Native Training
Topic: Optimizing Images, Assets, and Network Requests
Course Link: React Native Training at JustAcademy
Demo Registration Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Image, Asset, and Network Optimization
React Native applications commonly display product photos, profile pictures, banners, icons, illustrations, documents, and other media. They also communicate with remote servers to retrieve data, submit forms, authenticate users, and synchronize application state.
When images are too large, assets are unnecessarily duplicated, or network requests are poorly managed, an application can become slow, consume excessive memory and bandwidth, drain the battery, and provide a poor user experience.
Optimization means delivering the required content using appropriate image dimensions, efficient file formats, well-organized assets, predictable layouts, reliable network operations, and effective caching strategies.
Learning Objectives
- Understand how React Native handles local and remote images.
- Choose suitable image formats and resolutions.
- Reduce asset sizes and organize static resources effectively.
- Display image placeholders and handle loading failures.
- Understand HTTP requests, response handling, and error management.
- Reduce unnecessary network requests and duplicate API calls.
- Implement request cancellation, pagination, caching, and retry strategies.
- Measure image and network performance on real devices.
2. Understanding Images and Assets in React Native
An asset is a resource used by an application, such as an image, icon, font, audio file, or other static file. React Native supports bundled static images and dynamically loaded remote images.
2.1 Static Images
Static images are included in the application source and referenced using a statically known require() expression.
import React from 'react';
import { Image, View } from 'react-native';
export default function Logo() {
return (
<View>
<Image
source={require('./assets/logo.png')}
style={{ width: 120, height: 120 }}
resizeMode="contain"
/>
</View>
);
}
Static image references allow the Metro bundler to identify and package the referenced asset. The image path must be statically known; arbitrary dynamically constructed paths inside require() are not supported in the same way.
2.2 Remote Images
Remote images are downloaded from a server when the application needs to display them. They are useful for user profiles, product listings, news feeds, and other content that changes frequently.
import React from 'react';
import { Image } from 'react-native';
export default function ProfileImage() {
return (
<Image
source={{
uri: 'https://example.com/images/profile.jpg'
}}
style={{ width: 100, height: 100 }}
resizeMode="cover"
/>
);
}
Remote images generally need explicit dimensions. Setting the width and height helps React Native determine the space reserved for the image before the download completes.
2.3 Static vs. Remote Assets
| Feature |
Static Assets |
Remote Assets |
| Source |
Packaged with the application. |
Retrieved from a server or CDN. |
| Internet required |
Not required to load the bundled file. |
Usually required unless cached or stored locally. |
| Content updates |
Usually require an application update to replace the bundled file. |
Can be updated on the server independently. |
| Initial application size |
Can increase the installed application size. |
Can reduce bundled media size when fetched on demand. |
| Typical examples |
Logos, fixed icons, onboarding illustrations. |
Product photos, profile pictures, news thumbnails. |
3. Choosing the Correct Image Format
Image format affects file size, image quality, transparency, decoding cost, and compatibility. Selecting an appropriate format is an important part of application optimization.
| Format |
Common Uses |
Advantages |
Considerations |
| JPEG/JPG |
Photographs and product images. |
Often produces small files for photographs. |
Lossy compression can reduce quality; does not support transparency. |
| PNG |
Logos, interface illustrations, and transparent graphics. |
Supports lossless compression and transparency. |
Photographic images may be much larger than equivalent JPEG files. |
| WebP |
Photographs, illustrations, and transparent images. |
Can offer efficient lossy or lossless compression. |
Verify support for the target platform and the way the asset is bundled or delivered. |
| SVG |
Scalable icons and vector illustrations. |
Resolution-independent vector artwork. |
Rendering commonly requires a compatible SVG library or conversion into another asset format. |
| GIF |
Simple animations and legacy graphics. |
Supports basic animation. |
Limited color range; not ideal for most modern photographic media. |
Best Practices
- Use JPEG or an appropriate modern compressed format for photographs.
- Use PNG when lossless detail or transparency is required and its file size is reasonable.
- Use vector assets for simple scalable icons when suitable tooling is available.
- Compare visual quality and file size instead of choosing a format based on extension alone.
- Validate support on both Android and iOS.
4. Resize Images Before Uploading or Delivering Them
A common performance problem occurs when an application downloads a very large image and displays it in a small area. For example, downloading a 3000-by-3000-pixel photograph for a 90-by-90-pixel thumbnail wastes bandwidth and may increase memory pressure.
4.1 Serve Images at Appropriate Dimensions
Whenever possible, resize and compress images on the server or during the content publishing process. A backend or image CDN can generate thumbnail, medium, and full-size variants.
// Example API response
{
"id": "product-101",
"name": "Travel Backpack",
"thumbnailUrl": "https://cdn.example.com/backpack-160.jpg",
"imageUrl": "https://cdn.example.com/backpack-800.jpg"
}
Use the thumbnail URL in list views and the larger image URL on the product details screen.
4.2 Avoid Unnecessary Runtime Resizing
Set image dimensions based on the layout and avoid repeatedly changing image width and height during animations. Resizing large images can be computationally expensive. When animating a zoom effect, consider transforms when appropriate instead of continuously changing the image's dimensions.
5. Support Different Screen Densities
Mobile devices have different pixel densities. React Native supports image variants with suffixes such as @2x and @3x, allowing the bundler to select an appropriate resource for the device.
assets/
icon.png
[email protected]
[email protected]
Reference the base file using a static require:
<Image
source={require('./assets/icon.png')}
style={{ width: 32, height: 32 }}
/>
The example provides a 32-by-32 layout size. Supply appropriate higher-density files when necessary, while avoiding unnecessarily large or duplicated artwork. For remotely hosted images, the server can provide density-appropriate variants based on requested dimensions or URL parameters.
6. Optimize Static Asset Organization
A clear asset structure makes projects easier to maintain and helps developers identify which files are required by each screen.
6.1 Recommended Folder Structure
src/
assets/
images/
logo.png
onboarding.png
icons/
home.png
settings.png
fonts/
AppFont-Regular.ttf
components/
Logo.js
ProductCard.js
screens/
HomeScreen.js
ProductScreen.js
6.2 Asset Management Guidelines
- Group assets by type or feature.
- Use descriptive, consistent filenames.
- Remove unused images, duplicate files, and obsolete font files.
- Compress assets before including them in a release build.
- Keep image variants consistent and document their intended use.
- Check whether third-party assets introduce licensing requirements.
- Avoid importing large media files when a small icon or a simpler visual representation is sufficient.
7. Use Image Dimensions and resizeMode Correctly
The resizeMode property controls how an image fits within its container. Choosing the correct mode avoids unwanted stretching and unexpected layout results.
| Mode |
Behavior |
Typical Use |
cover |
Fills the container while preserving aspect ratio; some content may be cropped. |
Profile pictures and product cards. |
contain |
Fits the entire image inside the container while preserving aspect ratio. |
Logos and product images that must remain fully visible. |
stretch |
Stretches the image to fill the dimensions, potentially changing its proportions. |
Only where distortion is acceptable. |
center |
Centers the image without scaling it up; an oversized image may be scaled down. |
Specific layouts where original proportions and placement matter. |
repeat |
Repeats the image to fill the available area where supported. |
Tileable textures and repeating patterns. |
<Image
source={require('./assets/product.png')}
style={{ width: 180, height: 180 }}
resizeMode="contain"
/>
Providing explicit dimensions reduces layout uncertainty. For remote images with varying aspect ratios, calculate the height from the known aspect ratio or reserve a consistent image area.
8. Display Placeholders While Images Load
Remote images may take time to download or decode. Showing a placeholder keeps the interface visually stable and tells users that content is loading.
8.1 Using onLoadStart, onLoad, and onError
import React, { useState } from 'react';
import { ActivityIndicator, Image, View } from 'react-native';
export default function RemoteImage({ uri }) {
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
return (
<View
style={{
width: 160,
height: 160,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#eeeeee',
}}
>
{loading && !failed ? <ActivityIndicator /> : null}
{failed ? null : (
<Image
source={{ uri }}
style={{
width: 160,
height: 160,
position: 'absolute',
}}
resizeMode="cover"
onLoadStart={() => {
setLoading(true);
setFailed(false);
}}
onLoad={() => setLoading(false)}
onError={() => {
setLoading(false);
setFailed(true);
}}
/>
)}
</View>
);
}
This example tracks loading and failure states. A production component should also display a fallback icon or local placeholder when the request fails, and should be tested if the image URL changes while the component remains mounted.
9. Use Image Caching Appropriately
Image caching can avoid repeatedly downloading the same resource. Native platform caching behavior varies by platform, URL, request configuration, and React Native version.
9.1 Why Caching Matters
- Reduces repeated network transfers.
- Can improve the speed of revisiting screens.
- May reduce data consumption on mobile networks.
- Can improve perceived responsiveness when previously loaded images remain available.
9.2 Image Cache Options
Depending on the supported React Native version, an image source can expose cache strategies such as default behavior, reload, force-cache, and only-if-cached. Verify the exact options supported by the version and platform used in your project.
<Image
source={{
uri: 'https://example.com/images/product.jpg',
cache: 'force-cache',
}}
style={{ width: 120, height: 120 }}
/>
Important: A forced cache strategy can serve stale content. Use cache behavior according to the content's freshness requirements. If you need more predictable disk caching, prefetching, advanced image processing, or specialized request handling, evaluate a maintained image library compatible with your React Native setup.
10. Prefetch Images When Useful
Prefetching starts downloading an image before it is needed on screen. It can help when the application knows which images are likely to appear next, such as thumbnails for an upcoming product details page.
import { Image } from 'react-native';
async function prefetchProductImage(uri) {
try {
const cached = await Image.prefetch(uri);
return cached;
} catch (error) {
console.warn('Image prefetch failed:', error);
return false;
}
}
Prefetching Guidelines
- Prefetch only images likely to be needed soon.
- Avoid prefetching an entire large catalog at startup.
- Respect bandwidth and data-use considerations.
- Handle failures without blocking the main screen.
- Measure whether prefetching actually improves the user experience.
11. Understanding Network Requests in React Native
Network requests allow a mobile application to communicate with remote services. Common tasks include retrieving user profiles, loading product lists, sending login credentials, uploading files, and saving changes.
React Native supports APIs such as fetch() for HTTP requests. Other applications may use a compatible networking library when they need additional features such as interceptors, request cancellation helpers, or standardized response handling.
11.1 Basic GET Request
async function fetchProducts() {
const response = await fetch(
'https://example.com/api/products'
);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
Checking response.ok is important because fetch does not automatically reject its promise for ordinary HTTP error statuses such as 404 or 500. Network failures and aborts can reject the promise.
11.2 POST Request
async function createProduct(product) {
const response = await fetch(
'https://example.com/api/products',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(product),
}
);
if (!response.ok) {
throw new Error(`Unable to save product: ${response.status}`);
}
return response.json();
}
Always follow the server's API contract for headers, request body structure, authentication, and expected response formats.
12. Reduce Unnecessary Network Requests
Repeated requests waste bandwidth and can delay the user interface. A request should be made when its result is needed, rather than every time a component renders.
12.1 Avoid Fetching Directly During Rendering
// Avoid starting network requests directly in the render body.
function ProductScreen() {
// Calling fetch here on every render is a mistake.
return null;
}
Use an effect, event handler, or data-fetching solution designed to manage the request lifecycle.
12.2 Fetch Data with useEffect
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';
export default function ProductScreen() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
const controller = new AbortController();
async function loadProducts() {
try {
setLoading(true);
setError('');
const response = await fetch(
'https://example.com/api/products',
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
setProducts(data);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message || 'Unable to load products.');
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
loadProducts();
return () => controller.abort();
}, []);
if (loading) {
return <ActivityIndicator />;
}
if (error) {
return <Text>{error}</Text>;
}
return (
<View>
{products.map((product) => (
<Text key={product.id}>{product.name}</Text>
))}
</View>
);
}
This example assumes the API returns an array of products. Adapt the response parsing to the actual API format. Aborting the request during cleanup helps avoid unnecessary work when the component unmounts. Development Strict Mode can run effect setup and cleanup more than once to help identify unsafe effects, so development network logs may not match a production session exactly.
13. Cancel Requests That Are No Longer Needed
Request cancellation is especially important for search fields, rapidly changing filters, and screens that may be closed before a response arrives.
Example: Cancel an Outdated Search
async function searchProducts(query, signal) {
const url =
'https://example.com/api/products?q=' +
encodeURIComponent(query);
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error('Search request failed.');
}
return response.json();
}
Create an AbortController for a request and pass its signal to fetch. When a newer search replaces an older one, abort the older request where supported. Also ensure that stale responses cannot overwrite the latest results.
14. Implement Debouncing for Search Requests
When users type into a search field, sending a request for every keystroke can create unnecessary server load. Debouncing waits for a short period of inactivity before triggering the search.
import React, { useEffect, useState } from 'react';
function useDebouncedValue(value, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(timeoutId);
}, [value, delay]);
return debouncedValue;
}
Use the debounced value as the input to the search request. The debounce interval is a design choice; adjust it to balance responsiveness with the number of requests. For network searches, combine debouncing with cancellation and stale-response protection.
15. Implement Pagination for Large API Responses
Downloading a very large response can increase startup time, memory usage, and bandwidth consumption. Pagination retrieves smaller portions of data as users need them.
Common Pagination Strategies
| Strategy |
Description |
Typical Use |
| Page number |
Requests a numbered page and a page size. |
Simple catalogs and admin lists. |
| Offset and limit |
Requests a range of records starting at a specified offset. |
APIs that support offset-based access. |
| Cursor-based |
Requests records after a cursor returned by the server. |
Feeds and collections that change frequently. |
| Infinite scrolling |
Requests the next portion as the user approaches the end of a list. |
Social feeds and product browsing. |
Example Request
const response = await fetch(
'https://example.com/api/products?page=2&limit=20'
);
Pagination reduces the amount of data transferred at once, but it should be paired with deduplication, loading state, retry handling, and a clear indication that more data is available.
16. Cache API Responses
Response caching allows the application to reuse data rather than downloading it again when the same screen is revisited. Caching can improve perceived speed and reduce network traffic.
16.1 Common Caching Approaches
- In-memory cache: Keeps data in JavaScript memory for quick access during the current application session.
- Persistent cache: Stores selected data on the device for use across application restarts.
- HTTP caching: Uses server response headers and client networking behavior to manage freshness and revalidation.
- Query cache: A data-fetching library stores query results and manages invalidation, refetching, and shared requests.
16.2 Example: Simple In-Memory Cache
const responseCache = new Map();
async function getCachedJson(url) {
if (responseCache.has(url)) {
return responseCache.get(url);
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
responseCache.set(url, data);
return data;
}
This is a minimal illustration, not a complete production cache. It has no expiration, size limit, invalidation, persistent storage, or protection against duplicate simultaneous requests. A production implementation should define when cached data becomes stale and how it is refreshed.
17. Understand Cache Invalidation and Freshness
Cached data may become outdated when users change their profiles, products are updated, or permissions change. The application needs a strategy for refreshing stale data and invalidating data after mutations.
- Use expiration times where appropriate.
- Honor server-provided caching headers when supported by the client.
- Invalidate related cache entries after successful updates.
- Refresh data when users explicitly request it or return to a screen, if appropriate.
- Do not cache sensitive responses in shared or insecure storage.
- Keep user-specific cache entries separated by account or session.
18. Handle Network Errors and Retries
Network requests can fail because of poor connectivity, server errors, timeouts, authentication problems, rate limits, or malformed responses. Error handling should give users a useful recovery path without creating repeated unnecessary requests.
| Error Type |
Possible Cause |
Recommended Action |
| Network failure |
Offline device, DNS failure, or connection interruption. |
Show a retry option and preserve user input. |
| HTTP 400 |
Invalid request parameters or malformed input. |
Correct the request or display a validation message. |
| HTTP 401 |
Missing or expired authentication. |
Refresh credentials where appropriate or ask the user to sign in again. |
| HTTP 403 |
The user lacks permission. |
Explain that access is unavailable; do not retry blindly. |
| HTTP 404 |
Resource does not exist. |
Show an appropriate not-found state. |
| HTTP 429 |
Rate limit exceeded. |
Respect Retry-After when provided and apply backoff. |
| HTTP 500-range |
Server-side failure. |
Retry selectively if the operation is safe to repeat. |
| Aborted request |
The user changed screens or replaced the request. |
Usually treat it as expected cancellation rather than a user-facing error. |
18.1 Retry with Exponential Backoff
Exponential backoff increases the wait between repeated attempts. Adding random jitter helps prevent many clients from retrying at the same time.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function fetchWithRetry(url, attempts = 3) {
let lastError;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const response = await fetch(url);
if (response.ok) {
return response;
}
// Retry selected transient HTTP failures only.
if (
response.status !== 429 &&
response.status < 500
) {
throw new Error(`HTTP ${response.status}`);
}
lastError = new Error(`HTTP ${response.status}`);
} catch (error) {
lastError = error;
}
if (attempt < attempts - 1) {
const baseDelay = 500 * (2 ** attempt);
const jitter = Math.random() * 250;
await wait(baseDelay + jitter);
}
}
throw lastError || new Error('Request failed.');
}
This example illustrates a retry pattern and should be adapted for production. It does not handle an overall deadline, cancellation, or the server's Retry-After header. It also catches errors broadly; refine the policy so that permanent failures and user-triggered aborts are not retried. Do not automatically retry non-idempotent operations such as payment submissions unless the API provides an appropriate idempotency mechanism.
19. Optimize Network Payloads
The response size and the amount of data processed by JavaScript both influence performance. Return only the fields the screen needs and avoid transferring unnecessary nested objects.
Recommendations
- Use server-side pagination and filtering.
- Request only necessary fields when the API supports field selection.
- Compress responses where supported by the server and client.
- Avoid downloading full-resolution images for thumbnail views.
- Use efficient JSON structures and avoid redundant data.
- Keep payloads and image responses within practical limits for mobile networks.
- Use a CDN for geographically distributed static media where appropriate.
20. Avoid Duplicate Requests
Duplicate requests can occur when multiple components request the same data, effects run again, users tap repeatedly, or a list's end-reached callback fires more than once.
Prevention Strategies
- Track in-flight requests and share their results when appropriate.
- Disable or guard repeated submissions while a request is in progress.
- Use query keys and request deduplication in a suitable data-fetching library.
- Cancel obsolete requests and ignore stale responses.
- Use idempotency keys for sensitive operations when supported by the backend.
- Inspect development network logs to find repeated calls.
21. Secure Network Requests and Media
Performance improvements must not weaken application security. Use encrypted transport, protect authentication data, and validate information received from external services.
- Use HTTPS for APIs and remote images.
- Never hardcode secret API keys or private credentials into the mobile application.
- Store sensitive tokens using secure platform storage appropriate to the project.
- Do not include passwords or access tokens in URLs or diagnostic logs.
- Validate server responses before relying on their structure.
- Restrict access to private images using appropriate authorization and signed URLs when required.
- Respect authorization rules when caching user-specific data.
- Avoid disabling platform transport-security protections to make a request work.
22. Upload Images Efficiently
Applications that allow profile photos, receipts, or product images to be uploaded should consider file size, network reliability, progress feedback, and server validation.
Upload Optimization Checklist
- Resize large photographs to the maximum resolution needed by the product.
- Compress images while preserving acceptable visual quality.
- Use multipart uploads or a suitable upload API when required by the backend.
- Display upload progress when supported.
- Allow users to retry failed uploads.
- Prevent accidental duplicate submissions.
- Validate file type and size on both client and server.
- Consider resumable uploads for large files or unstable connections.
23. Measure Image and Network Performance
Optimization should be verified with realistic workloads rather than assumed from code changes alone.
Metrics to Observe
- Application startup time and time to first useful content.
- Image download and display latency.
- API response duration and failure rate.
- Total network bytes transferred.
- Number of duplicate and unnecessary requests.
- Memory usage during image-heavy navigation.
- Scrolling smoothness in lists containing remote images.
- Behavior on slow connections and offline devices.
Testing Process
- Record the current behavior before making changes.
- Test on physical Android and iOS devices where possible.
- Use realistic image sizes and a representative network environment.
- Inspect requests with React Native DevTools or suitable platform tools.
- Test loading, errors, retries, cancellation, and cache behavior.
- Compare measurements after each optimization.
- Repeat testing with a production-like build.
24. Common Problems and Solutions
| Problem |
Likely Cause |
Solution |
| Images load slowly |
Large files, slow server, or distant image host. |
Resize images, compress files, use thumbnails, and consider a CDN. |
| Image dimensions change after loading |
Remote image has no reserved layout dimensions. |
Define dimensions or calculate height from the aspect ratio. |
| Images repeatedly download |
Cache behavior, changing URLs, or missing cache support. |
Review cache headers, URL stability, and platform behavior. |
| Screen makes many API calls |
Requests are triggered during rendering or effects have incorrect dependencies. |
Move requests to appropriate lifecycle logic and deduplicate calls. |
| Old search results replace new results |
Requests finish out of order. |
Cancel old requests or verify a request ID before updating state. |
| Application uses too much memory |
Oversized images or excessive data retained in memory. |
Use appropriately sized images, pagination, and bounded caches. |
| Repeated retries overload the API |
No retry limits or aggressive retry timing. |
Use bounded exponential backoff and respect rate-limit instructions. |
| App fails offline |
Every screen depends on a live network request. |
Provide cached content, offline messaging, and retry options as appropriate. |
25. Practical Project: Optimized Product Gallery
Project Objective: Build a React Native product gallery that loads images efficiently and retrieves product information from an API.
Requirements
- Create a product model with ID, title, price, thumbnail URL, and full-size image URL.
- Display products using FlatList.
- Use thumbnail images in the list and larger images on the detail screen.
- Provide image dimensions and loading placeholders.
- Display a fallback when an image fails to load.
- Fetch product data using asynchronous requests.
- Implement loading, error, retry, and empty states.
- Use pagination to load additional products.
- Prevent duplicate requests and handle obsolete requests.
- Implement a suitable cache policy for frequently viewed data.
- Measure request duration, image-loading behavior, and scrolling performance.
Expected Result
The application should display images without unnecessary layout shifts, load data in manageable portions, handle network failures gracefully, avoid redundant requests, and remain responsive during scrolling and navigation.
26. Interview Questions and Answers
Q1. What is the difference between a local image and a remote image?
Answer: A local image is included in or stored with the application, while a remote image is retrieved from a URL or server. Remote images require explicit dimensions and appropriate loading and failure handling.
Q2. Why should images be resized before being displayed?
Answer: Smaller, appropriately sized images reduce bandwidth consumption and can reduce memory and decoding costs.
Q3. What is the purpose of resizeMode?
Answer: It controls how an image fits within its container, including whether the image is cropped, contained, stretched, centered, or repeated.
Q4. What is image caching?
Answer: Image caching stores or reuses previously retrieved image data to reduce repeated downloads and improve loading speed.
Q5. What is image prefetching?
Answer: Prefetching downloads an image before it is needed, potentially reducing the delay when the image is later displayed.
Q6. Why does fetch not automatically reject for every HTTP error?
Answer: HTTP responses such as 404 and 500 still resolve the fetch promise. The application should inspect response.ok or response.status and handle the response appropriately.
Q7. What is request cancellation?
Answer: Request cancellation stops unnecessary work when a result is no longer needed, such as when a user leaves a screen or changes a search query.
Q8. What is debouncing?
Answer: Debouncing delays an operation until a specified period of inactivity has passed. It is often used to reduce excessive search requests while users type.
Q9. What is API pagination?
Answer: Pagination divides a large collection into smaller responses, improving initial loading and reducing the amount of data transferred at once.
Q10. What is exponential backoff?
Answer: It increases the waiting time between retry attempts. Adding jitter and limiting retries helps avoid synchronized retry bursts.
Q11. Why is HTTPS important?
Answer: HTTPS encrypts communication between the client and server, helping protect data in transit and supporting platform transport-security requirements.
Q12. How do you debug slow network requests?
Answer: Inspect request timing, response size, server latency, duplicate requests, and failures with React Native DevTools or appropriate platform tools. Compare results under realistic network conditions.
27. Quick Revision Checklist
- Use appropriate image formats and dimensions.
- Provide static assets through statically known require references.
- Use @2x and @3x assets where appropriate.
- Set dimensions for remote images.
- Display placeholders and error fallbacks.
- Use caching and prefetching when they provide measurable benefits.
- Fetch data in effects or event handlers rather than during rendering.
- Check HTTP response status and handle failures.
- Cancel obsolete requests and protect against stale responses.
- Use pagination and debouncing where appropriate.
- Implement cache expiration and invalidation.
- Use bounded retries and respect rate limits.
- Protect authentication credentials and use HTTPS.
- Measure memory, network traffic, and image-loading performance.
28. Official Learning Resources
29. Conclusion
Optimizing images, assets, and network requests is essential for building fast, reliable React Native applications. Correct image dimensions and compression reduce media costs, while organized assets improve maintainability. Efficient requests, pagination, cancellation, caching, and sensible retry behavior reduce unnecessary network work and make the application more resilient.
The best optimization strategy depends on the application, the devices it supports, the size of its content, and the behavior of its backend. Measure performance, test on real devices, and improve the largest bottlenecks first.
Explore React Native Training: View the React Native Course at JustAcademy
Register for a Demo: Register for a Course Demo
Visit JustAcademy: https://www.justacademy.co/